


import 'package:erp/Entity/Supplier.dart';
import 'package:erp/Entity/SupplierType.dart';
import 'package:erp/Events/EventAddrs.dart';
import 'package:erp/Store/AccountStore.dart';
import 'package:erp/Store/SupplierStore.dart';
import 'package:erp/global.dart';

void registerSupplierEvents(){
  globalBus.subscribe(Events.SUPPLIER_SELECT_REQUEST, (bus, _) async {
    try {
      var pageCount = await externalInterface.getAllSupplierCount(AccountStore.signInResult.token);
      var suppliers = <Supplier>[];
      for (var index = 0; index < pageCount.allPageCount; index++){
        var items = await externalInterface.getSuppliers(AccountStore.signInResult.token, index);
        suppliers.addAll(items);
      }
      SupplierStore.suppliers = suppliers;
      globalBus.publish(Events.SUPPLIER_SELECT_SUCCESS, suppliers);
    }
    catch (exception){
      globalBus.publish(Events.SUPPLIER_SELECT_ERROR, exception);
    }
  });

  globalBus.subscribe<Supplier>(Events.SUPPLIER_INSERT_REQUEST, (bus, supplier) async {
    try{
      var data = await externalInterface.addSupplier(AccountStore.signInResult.token, supplier);
      SupplierStore.suppliers.add(data);
      globalBus.publish(Events.SUPPLIER_INSERT_SUCCESS, data);
    }
    catch (exception){
      globalBus.publish(Events.SUPPLIER_INSERT_ERROR, exception);
    }
  });

  globalBus.subscribe<Supplier>(Events.SUPPLIER_UPDATE_REQUEST, (bus, supplier) async {
    try {
      var data = await externalInterface.updateSupplier(AccountStore.signInResult.token, supplier);
      var index = SupplierStore.suppliers.indexWhere((item) => item.id == data.id);
      SupplierStore.suppliers[index] = data;
      globalBus.publish(Events.SUPPLIER_UPDATE_SUCCESS, data);
    }
    catch (exception){
      globalBus.publish(Events.SUPPLIER_UPDATE_ERROR, exception);
    }
  });

  globalBus.subscribe<Supplier>(Events.SUPPLIER_DELETE_REQUEST, (bus, supplier) async {
    try {
      var data = await externalInterface.deleteSupplier(AccountStore.signInResult.token, supplier);
      SupplierStore.suppliers.removeWhere((item) => item.id == data.id);
      globalBus.publish(Events.SUPPLIER_DELETE_SUCCESS, data);
    }
    catch (exception) {
      globalBus.publish(Events.SUPPLIER_DELETE_ERROR, exception);
    }
  });
}









